﻿# 绘制组图的 像素点灰度值随曝光时间变化关系(随机取100点) 并且：
# 检查合成tiff图片时间和像素亮度是否一致
import os
import sys
import re
import cv2
import numpy as np
import matplotlib.pyplot as plt
import random

# plt.rcParams['font.sans-serif'] = ['Simhei']  # 用来正常显示中文标签
plt.rcParams['font.sans-serif'] = ['Simsun']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
plt.rcParams['figure.figsize'] = [28, 10]
plt.rcParams.update(
    {
        'text.usetex': False,
        # 'font.family': 'stixgeneral',
        'mathtext.fontset': 'stix',
        "font.size": 28
    }
)

pic_path = input("输入组图文件夹路径(无最后的\\):")
print("结果将保存到".format(pic_path))  # 无最后的\
# pic_path = r'C:\Users\17616\Desktop\本科毕设\实验数据记录\2021-5-20\G0_0-F4-0520\G0_0-LD4I2'


csv_file = open(pic_path + "/CheckSrcResult.csv", 'w')


def cv_imread(file_path):
    cv_img = cv2.imdecode(np.fromfile(file_path, dtype=np.uint8), -1)
    return cv_img


def find_exp_time(img):
    s = re.findall("\d+us", img)[0]
    s = re.findall("\d+", s)[0]
    return int(s)
    # print(s)


reorder_map = np.array([], dtype=np.int64)


def CreateReorderMap(us):
    map = np.array(us, dtype=np.int64)
    size = map.shape[0]
    for i in range(size):
        map[i] = i
    for i in range(size):
        # Last i elements are already in place
        for j in range(0, size - i - 1):
            if us[map[j]] > us[map[j + 1]]:
                map[j], map[j + 1] = map[j + 1], map[j]
    print("us:", end=' ')
    for i in range(size):
        print(us[map[i]], end=' ')
        csv_file.write("%dus," % us[map[i]])
    print("")
    csv_file.write('\n')
    return map


def reorder(x1, y1):
    x = x1.copy()
    y = y1.copy()
    size = x.shape[0]
    for i in range(size):
        x[i] = x1[reorder_map[i]]
        y[i] = y1[reorder_map[i]]
        csv_file.write("%d," % y[i])
    csv_file.write('\n')
    idx = np.where(y == 0)[0]
    np.delete(x, idx)
    np.delete(y, idx)
    return x, y


list = []  # 设置一个空列表用于接收
list = os.listdir(pic_path)  # os.listdir() 用于获取此文件下所有文件名
pic_names = []
exps = []  # 曝光时间
pics = []
for item in list:
    if item.find('.png') != -1 and item.find('us') != -1:
        pic_names.append(item)
        exps.append(find_exp_time(item))
        pics.append(cv_imread(pic_path + '\\' + item))

pics = np.stack(pics, 0)
exps = np.array(exps, dtype=np.int64)
reorder_map = CreateReorderMap(exps)
imgH = pics.shape[-1]
imgV = pics.shape[-2]

plt.figure(figsize=(25, 15))

for i in range(1000):
    x, y = reorder(exps, pics[:, random.randint(0, imgV - 1), random.randint(0, imgH - 1)])
    plt.loglog(x, y, marker='.', nonpositive='mask')

plt.xlabel("曝光时间(us)")
plt.ylabel("灰度值")
plt.title('像素点灰度值随曝光时间变化关系(随机取100点)')
csv_file.close()
plt.show()
# print(pics)  # 查看
